<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="profile-header">
      <h1>个人中心</h1>
    </div>

    <!-- 主要内容区域 -->
    <div class="profile-content">
      <!-- 侧边栏导航 -->
      <div class="profile-sidebar">
        <el-menu 
          :default-active="activeTab" 
          class="profile-menu" 
          mode="vertical"
          @select="handleTabChange"
        >
          <el-menu-item index="info">
            <el-icon><user /></el-icon>
            <span>基本信息</span>
          </el-menu-item>
          <el-menu-item index="orders">
            <el-icon><document /></el-icon>
            <span>我的订单</span>
          </el-menu-item>
          <el-menu-item index="address">
            <el-icon><location /></el-icon>
            <span>收货地址</span>
          </el-menu-item>
          <el-menu-item index="security">
            <el-icon><lock /></el-icon>
            <span>账户安全</span>
          </el-menu-item>
          <el-menu-item index="favorites">
            <el-icon><star /></el-icon>
            <span>我的收藏</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区 -->
      <div class="profile-main">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton v-if="loading" :rows="5" animated />
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error-container">
          <el-alert :title="error" type="error" show-icon />
        </div>

        <!-- 基本信息标签页 -->
        <div v-else-if="activeTab === 'info'" class="info-tab">
          <div class="user-info-card">
            <div class="user-avatar-section">
              <el-avatar :size="120" class="user-avatar">
                <img :src="userInfo.avatar || defaultAvatar" :alt="userInfo.username" />
              </el-avatar>
              <div class="user-basic-info">
                <h2>{{ userInfo.username }}</h2>
                <p class="user-email">{{ userInfo.email }}</p>
                <p class="user-level">用户等级: {{ userInfo.level || '普通用户' }}</p>
              </div>
            </div>

            <el-divider />

            <!-- 个人信息表单 -->
            <el-form 
              ref="infoFormRef" 
              :model="editUserInfo" 
              :rules="infoFormRules" 
              label-width="100px"
              class="info-form"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="editUserInfo.username" :disabled="!isEditingInfo" />
              </el-form-item>
              
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="editUserInfo.nickname" :disabled="!isEditingInfo" />
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editUserInfo.email" type="email" :disabled="!isEditingInfo" />
              </el-form-item>
              
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="editUserInfo.gender" :disabled="!isEditingInfo">
                  <el-radio label="male">男</el-radio>
                  <el-radio label="female">女</el-radio>
                  <el-radio label="other">其他</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="editUserInfo.birthday"
                  type="date"
                  placeholder="选择生日"
                  :disabled="!isEditingInfo"
                  class="w-full"
                />
              </el-form-item>
              
              <el-form-item label="手机" prop="phone">
                <el-input v-model="editUserInfo.phone" :disabled="!isEditingInfo" />
              </el-form-item>
              
              <el-form-item>
                <div v-if="!isEditingInfo">
                  <el-button type="primary" @click="startEditInfo">编辑资料</el-button>
                </div>
                <div v-else>
                  <el-button type="primary" @click="saveUserInfo">保存</el-button>
                  <el-button @click="cancelEditInfo">取消</el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 订单标签页 -->
        <div v-else-if="activeTab === 'orders'" class="orders-tab">
          <div class="order-tabs">
            <el-tabs v-model="orderStatus" @tab-change="fetchOrders">
              <el-tab-pane label="全部订单" name="all" />
              <el-tab-pane label="待付款" name="pending_payment" />
              <el-tab-pane label="待发货" name="pending_shipment" />
              <el-tab-pane label="待收货" name="pending_receipt" />
              <el-tab-pane label="已完成" name="completed" />
              <el-tab-pane label="已取消" name="cancelled" />
            </el-tabs>
          </div>

          <!-- 订单列表 -->
          <div v-if="orders.length > 0" class="orders-list">
            <div v-for="order in orders" :key="order.id" class="order-item">
              <div class="order-header">
                <span class="order-number">订单编号: {{ order.id }}</span>
                <span class="order-status">{{ getOrderStatusText(order.status) }}</span>
                <span class="order-time">{{ formatDate(order.createdAt) }}</span>
              </div>
              
              <div class="order-products">
                <div v-for="item in order.orderItems" :key="item.id" class="order-product-item">
                  <img :src="item.productImage" :alt="item.productName" class="product-image" />
                  <div class="product-info">
                    <h4 class="product-name">{{ item.productName }}</h4>
                    <p class="product-specs" v-if="item.specifications">
                    {{ formatSpecifications(item.specifications) }}
                    </p>
                    <p class="product-price">¥{{ item.price }}</p>
                    <p class="product-quantity">数量: {{ item.quantity }}</p>
                  </div>
                </div>
              </div>
              
              <div class="order-footer">
                <span class="order-total">总金额: ¥{{ order.totalAmount }}</span>
                <el-button size="small" @click="viewOrderDetail(order.id)">查看详情</el-button>
              </div>
            </div>
          </div>
          
          <div v-else class="no-orders">
            <p>暂无订单</p>
          </div>
        </div>
        
        <!-- 收货地址标签页 -->
        <div v-else-if="activeTab === 'address'" class="address-tab">
          <div class="address-header">
            <el-button type="primary" @click="showAddressForm">新增地址</el-button>
          </div>
          
          <div class="address-list">
            <div 
              v-for="address in (addresses || [])" 
              :key="address.id" 
              class="address-item"
              :class="{ 'default-address': address.isDefault }"
            >
              <div class="address-info">
                <div class="address-contact">
                  <span class="address-name">{{ address.name }}</span>
                  <span class="address-phone">{{ address.phone }}</span>
                </div>
                <div class="address-detail">
                  {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
                </div>
                <div class="address-actions">
                  <el-tag v-if="address.isDefault" type="success">默认地址</el-tag>
                </div>
              </div>
              <div class="address-operations">
                <el-button link @click="editAddress(address)">编辑</el-button>
                <el-button link @click="deleteAddress(address.id)">删除</el-button>
                <el-button v-if="!address.isDefault" link @click="setDefaultAddress(address.id)">设为默认</el-button>
              </div>
            </div>
            
            <div v-if="(addresses && addresses.length === 0) || !addresses" class="no-address">
              <p>暂无收货地址</p>
            </div>
          </div>
          
          <!-- 地址表单弹窗 -->
          <el-dialog v-model="addressDialogVisible" :title="editingAddress.id ? '编辑地址' : '新增地址'" width="500px">
            <el-form 
              ref="addressFormRef" 
              :model="editingAddress" 
              :rules="addressFormRules" 
              label-width="80px"
            >
              <el-form-item label="姓名" prop="name">
                <el-input v-model="editingAddress.name" />
              </el-form-item>
              
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="editingAddress.phone" />
              </el-form-item>
              
              <el-form-item label="地区" prop="area">
                <el-cascader
                  v-model="selectedArea"
                  :options="areaOptions"
                  :props="{ expandTrigger: 'hover' }"
                  @change="handleAreaChange"
                />
              </el-form-item>
              
              <el-form-item label="详细地址" prop="detail">
                <el-input v-model="editingAddress.detail" type="textarea" />
              </el-form-item>
              
              <el-form-item label="默认地址">
                <el-switch v-model="editingAddress.isDefault" />
              </el-form-item>
            </el-form>
            
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="addressDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveAddress">保存</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        
        <!-- 账户安全标签页 -->
        <div v-else-if="activeTab === 'security'" class="security-tab">
          <el-card class="security-card">
            <template #header>
              <div class="card-header">
                <span>修改密码</span>
              </div>
            </template>
            
            <el-form 
              ref="passwordFormRef" 
              :model="passwordForm" 
              :rules="passwordFormRules" 
              label-width="100px"
              class="password-form"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword" type="password" show-password />
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" show-password />
              </el-form-item>
              
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="changePassword">确认修改</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          
          <el-card class="security-card">
            <template #header>
              <div class="card-header">
                <span>绑定手机</span>
              </div>
            </template>
            
            <div class="binding-info">
              <div class="info-item">
                <span>当前绑定手机号：</span>
                <span>{{ userInfo.phone || '未绑定' }}</span>
              </div>
              <el-button type="primary" @click="showPhoneDialog">更换手机</el-button>
            </div>
          </el-card>
          
          <el-card class="security-card">
            <template #header>
              <div class="card-header">
                <span>绑定邮箱</span>
              </div>
            </template>
            
            <div class="binding-info">
              <div class="info-item">
                <span>当前绑定邮箱：</span>
                <span>{{ userInfo.email || '未绑定' }}</span>
              </div>
              <el-button type="primary" @click="showEmailDialog">更换邮箱</el-button>
            </div>
          </el-card>
          
          <!-- 手机绑定弹窗 -->
          <el-dialog v-model="phoneDialogVisible" title="更换手机" width="400px">
            <el-form 
              ref="phoneFormRef" 
              :model="phoneForm" 
              :rules="phoneFormRules"
              label-width="80px"
            >
              <el-form-item label="新手机号" prop="newPhone">
                <el-input v-model="phoneForm.newPhone" />
              </el-form-item>
              
              <el-form-item label="验证码" prop="phoneCode">
                <div class="code-input">
                  <el-input v-model="phoneForm.phoneCode" />
                  <el-button 
                    :disabled="phoneCodeTimer > 0" 
                    @click="sendPhoneCode"
                  >
                    {{ phoneCodeTimer > 0 ? `${phoneCodeTimer}秒后重发` : '发送验证码' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
            
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="phoneDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="bindNewPhone">确认绑定</el-button>
              </span>
            </template>
          </el-dialog>
          
          <!-- 邮箱绑定弹窗 -->
          <el-dialog v-model="emailDialogVisible" title="更换邮箱" width="400px">
            <el-form 
              ref="emailFormRef" 
              :model="emailForm" 
              :rules="emailFormRules"
              label-width="80px"
            >
              <el-form-item label="新邮箱" prop="newEmail">
                <el-input v-model="emailForm.newEmail" type="email" />
              </el-form-item>
              
              <el-form-item label="验证码" prop="emailCode">
                <div class="code-input">
                  <el-input v-model="emailForm.emailCode" />
                  <el-button 
:disabled="emailCodeTimer > 0" 
                    @click="sendEmailCode"
                  >
                    {{ emailCodeTimer > 0 ? `${emailCodeTimer}秒后重发` : '发送验证码' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
            
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="emailDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="bindNewEmail">确认绑定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        
        <!-- 其他标签页可以在这里继续添加 -->
        <div v-else class="empty-tab">
          <p>请选择一个标签页</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  getAddresses, 
  createAddress, 
  updateAddress, 
  deleteAddress as deleteAddressAPI,
  setDefaultAddress as setDefaultAddressAPI
} from '@/api/userService';

export default {
  name: 'UserProfile',
  data() {
    return {
      activeTab: 'info',
      loading: false,
      error: '',
      orderStatus: 'all',
      orders: [],
      addresses: [],
      userInfo: {},
      editUserInfo: {},
      isEditingInfo: false,
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      
      // 地址相关数据
      addressDialogVisible: false,
      editingAddress: {
        id: null,
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: false
      },
      selectedArea: [],
      areaOptions: [
        {
          value: '北京市',
          label: '北京市',
          children: [
            {
              value: '北京市',
              label: '北京市',
              children: [
                { value: '东城区', label: '东城区' },
                { value: '西城区', label: '西城区' },
                { value: '朝阳区', label: '朝阳区' },
                { value: '海淀区', label: '海淀区' }
              ]
            }
          ]
        }
      ],
      
      // 表单验证规则
      infoFormRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]
      },
      
      addressFormRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        detail: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
      },
      
      // 安全相关数据
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      
      phoneForm: {
        newPhone: '',
        phoneCode: ''
      },
      
      emailForm: {
        newEmail: '',
        emailCode: ''
      },
      
      phoneDialogVisible: false,
      emailDialogVisible: false,
      
      phoneCodeTimer: 0,
      emailCodeTimer: 0,
      
      passwordFormRules: {
        oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      
      phoneFormRules: {
        newPhone: [
          { required: true, message: '请输入新手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        phoneCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      
      emailFormRules: {
        newEmail: [
          { required: true, message: '请输入新邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        emailCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    };
  },
  methods: {
    handleTabChange(tab) {
      this.activeTab = tab;
      if (tab === 'address') {
        this.fetchAddresses();
      }
    },
    
    getOrderStatusText(status) {
      const statusMap = {
        'pending_payment': '待付款',
        'pending_shipment': '待发货',
        'pending_receipt': '待收货',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    
    formatDate(date) {
      return new Date(date).toLocaleDateString();
    },
    
    formatSpecifications(specs) {
      return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ');
    },
    
    startEditInfo() {
      this.isEditingInfo = true;
    },
    
    saveUserInfo() {
      this.isEditingInfo = false;
    },
    
    cancelEditInfo() {
      this.isEditingInfo = false;
    },
    
    fetchOrders() {
      // 获取订单数据的方法
    },
    
    viewOrderDetail(orderId) {
      // 查看订单详情的方法
    },
    
    // 地址相关方法
    async fetchAddresses() {
      try {
        const data = await getAddresses();
        this.addresses = data || []; // 确保addresses始终为数组
      } catch (err) {
        this.$message.error('获取地址列表失败');
        console.error('Failed to fetch addresses:', err);
        this.addresses = []; // 出错时设置为空数组
      }
    },
    
    showAddressForm() {
      this.editingAddress = {
        id: null,
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: false
      };
      this.selectedArea = [];
      this.addressDialogVisible = true;
    },
    
    editAddress(address) {
      this.editingAddress = { ...address };
      this.selectedArea = [address.province, address.city, address.district];
      this.addressDialogVisible = true;
    },
    
    async deleteAddress(id) {
      try {
        await this.$confirm('确认删除该地址吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await deleteAddressAPI(id);
        this.$message.success('删除成功');
        this.fetchAddresses();
      } catch (err) {
        if (err !== 'cancel') {
          this.$message.error('删除失败');
          console.error('Failed to delete address:', err);
        }
      }
    },
    
    async setDefaultAddress(id) {
      try {
        await setDefaultAddressAPI(id);
        this.$message.success('设置成功');
        this.fetchAddresses();
      } catch (err) {
        this.$message.error('设置失败');
        console.error('Failed to set default address:', err);
      }
    },
    
    handleAreaChange(val) {
      if (val && val.length === 3) {
        this.editingAddress.province = val[0];
        this.editingAddress.city = val[1];
        this.editingAddress.district = val[2];
      }
    },
    
    // 保存地址
    async saveAddress() {
      if (!this.$refs.addressFormRef) return;
      
      try {
        await this.$refs.addressFormRef.validate();
        
        // 准备地址数据
        const addressData = {
          name: this.editingAddress.name,
          phone: this.editingAddress.phone,
          province: this.editingAddress.province,
          city: this.editingAddress.city,
          district: this.editingAddress.district,
          detail: this.editingAddress.detail,
          isDefault: this.editingAddress.isDefault
        };
        
        // 保存地址
        if (this.editingAddress.id) {
          // 更新地址
          await updateAddress(this.editingAddress.id, addressData);
        } else {
          // 创建地址
          await createAddress(addressData);
        }
        
        this.$message.success(this.editingAddress.id ? '更新成功' : '创建成功');
        this.addressDialogVisible = false;
        this.fetchAddresses(); // 重新获取地址列表
      } catch (err) {
        console.error('Failed to save address:', err);
        this.$message.error('保存失败: ' + (err.message || '未知错误'));
      }
    },
    
    // 安全相关方法
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    
    changePassword() {
      this.$refs.passwordFormRef.validate((valid) => {
        if (valid) {
          // 修改密码逻辑
          this.$message.success('密码修改成功');
        }
      });
    },
    
    showPhoneDialog() {
      this.phoneForm.newPhone = '';
      this.phoneForm.phoneCode = '';
      this.phoneDialogVisible = true;
    },
    
    showEmailDialog() {
      this.emailForm.newEmail = '';
      this.emailForm.emailCode = '';
      this.emailDialogVisible = true;
    },
    
    sendPhoneCode() {
      // 发送手机验证码逻辑
      this.phoneCodeTimer = 60;
      const timer = setInterval(() => {
        this.phoneCodeTimer--;
        if (this.phoneCodeTimer <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    
    sendEmailCode() {
      // 发送邮箱验证码逻辑
      this.emailCodeTimer = 60;
      const timer = setInterval(() => {
        this.emailCodeTimer--;
        if (this.emailCodeTimer <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    
    bindNewPhone() {
      this.$refs.phoneFormRef.validate((valid) => {
        if (valid) {
          // 绑定新手机逻辑
          this.phoneDialogVisible = false;
          this.$message.success('手机绑定成功');
        }
      });
    },
    
    bindNewEmail() {
      this.$refs.emailFormRef.validate((valid) => {
        if (valid) {
          // 绑定新邮箱逻辑
          this.emailDialogVisible = false;
          this.$message.success('邮箱绑定成功');
        }
      });
    }
  }
};
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-header h1 {
  margin-bottom: 20px;
}

.profile-content {
  display: flex;
  gap: 20px;
}

.profile-sidebar {
  width: 200px;
}

.profile-main {
  flex: 1;
}

.user-avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.info-form {
  max-width: 500px;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-item {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.order-products {
  margin-bottom: 10px;
}

.order-product-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-orders {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

/* 地址样式 */
.address-header {
  margin-bottom: 20px;
  text-align: right;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
}

.address-info {
  flex: 1;
}

.address-contact {
  margin-bottom: 10px;
}

.address-name {
  font-weight: bold;
  margin-right: 15px;
}

.address-detail {
  margin-bottom: 10px;
  color: #666;
}

.address-operations {
  display: flex;
  gap: 10px;
}

.no-address {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.code-input {
  display: flex;
  gap: 10px;
}

/* 安全设置样式 */
.security-card {
  margin-bottom: 20px;
}

.security-card .card-header {
  font-weight: bold;
}

.binding-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.binding-info .info-item {
  margin: 10px 0;
}

.password-form {
  max-width: 400px;
}
</style>